1   /*
2    * Copyright (C) 2007 The Guava Authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package com.google.common.collect;
18  
19  import com.google.common.annotations.GwtCompatible;
20  
21  import java.io.Serializable;
22  
23  import javax.annotation.Nullable;
24  
25  /** An ordering that treats {@code null} as less than all other values. */
26  @GwtCompatible(serializable = true)
27  final class NullsFirstOrdering<T> extends Ordering<T> implements Serializable {
28    final Ordering<? super T> ordering;
29  
30    NullsFirstOrdering(Ordering<? super T> ordering) {
31      this.ordering = ordering;
32    }
33  
34    @Override public int compare(@Nullable T left, @Nullable T right) {
35      if (left == right) {
36        return 0;
37      }
38      if (left == null) {
39        return RIGHT_IS_GREATER;
40      }
41      if (right == null) {
42        return LEFT_IS_GREATER;
43      }
44      return ordering.compare(left, right);
45    }
46  
47    @Override public <S extends T> Ordering<S> reverse() {
48      // ordering.reverse() might be optimized, so let it do its thing
49      return ordering.reverse().nullsLast();
50    }
51  
52    @SuppressWarnings("unchecked") // still need the right way to explain this
53    @Override public <S extends T> Ordering<S> nullsFirst() {
54      return (Ordering<S>) this;
55    }
56  
57    @Override public <S extends T> Ordering<S> nullsLast() {
58      return ordering.nullsLast();
59    }
60  
61    @Override public boolean equals(@Nullable Object object) {
62      if (object == this) {
63        return true;
64      }
65      if (object instanceof NullsFirstOrdering) {
66        NullsFirstOrdering<?> that = (NullsFirstOrdering<?>) object;
67        return this.ordering.equals(that.ordering);
68      }
69      return false;
70    }
71  
72    @Override public int hashCode() {
73      return ordering.hashCode() ^ 957692532; // meaningless
74    }
75  
76    @Override public String toString() {
77      return ordering + ".nullsFirst()";
78    }
79  
80    private static final long serialVersionUID = 0;
81  }